package com.cloudkinto.controller.orderinput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.orderinput.OrderInputService;
import com.cloudkinto.service.orderinput.vo.OrderInputAddReq;
import com.cloudkinto.service.orderinput.vo.OrderInputExportRequest;
import com.cloudkinto.service.orderinput.vo.OrderInputUpdateReq;
import com.cloudkinto.service.product.ProductInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-08
 */
@RestController
@Api(tags = "订单入库模块")
@RequestMapping("/api/orderInput")
public class OrderInputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderInputController.class);

    @Autowired
    private OrderInputService service;
    @Autowired
    private ProductInfoService productInfoService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated OrderInputAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id, getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderInputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "shopId", value = "店铺id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String status = request.getParameter("status");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String keyword = request.getParameter("keyword");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("companyId", companyId + "");
        map.put("status", status);
        if (getShopId() != null)
            shopId = String.valueOf(getShopId());
        map.put("shopId", shopId);
        map.put("storageId", storageId);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productListPage")
    @ApiOperation(value = "商品（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult productListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String productType = request.getParameter("productType");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");

        map.put("companyId", String.valueOf(companyId));
        map.put("productType", productType);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return productInfoService.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入入库单信息", notes = "导入入库单信息")
    public SingleResult uploadExcel(MultipartFile file) throws IOException {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.importExcel(file, getCompanyId()));
    }

    @UserSessionRequired
    @PostMapping("/exportExcel")
    @ApiOperation(value = "导出入库单信息", notes = "导出入库单信息")
    public void exportExcel(@RequestBody OrderInputExportRequest request, HttpServletResponse response) throws IOException {
        Long userId = getCurrentUserId();
        service.exportExcel(request.getIds(), getCompanyId(), response);
    }

    @UserSessionRequired
    @GetMapping("/exportPackagePdf")
    @ApiOperation(value = "导出箱标文件", notes = "导出箱标文件")
    public void exportPackagePdf(Long id, Integer type, Boolean showCountry, HttpServletResponse response) throws IOException {
        Long userId = getCurrentUserId();
        service.exportPackagePdf(id, type == null ? 0 : type, showCountry == null || showCountry, response);
    }

    @UserSessionRequired
    @GetMapping("/exportProductPdf")
    @ApiOperation(value = "导出產品标文件", notes = "导出產品标文件")
    public void exportProductPdf(Long id, HttpServletResponse response) throws IOException {
        Long userId = getCurrentUserId();
        SingleResult.success(service.exportProductCodePdf(id, response));
    }

    @GetMapping("/logo/{id}.jpg")
    @ApiOperation(value = "", notes = "导出產品标文件")
    public void testpng(@PathVariable("id") String id, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        logger.debug(id);
        response.setHeader("content-Type", "image/png");
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test" + "." + "png", "UTF-8"));
        File file = new File("C:\\Users\\Administrator\\Pictures\\1.jpg");
        FileInputStream inputStream = new FileInputStream(file);
        int length = inputStream.available();
        byte data[] = new byte[length];
        response.setContentLength(length);
        inputStream.read(data);
        OutputStream toClient = response.getOutputStream();
        toClient.write(data);
        toClient.flush();
    }

    @UserSessionRequired
    @GetMapping("fbaReturnInit")
    @ApiOperation(value = "fba转运初始化", notes = "fba转运")
    public SingleResult fbaReturnInit(@RequestParam(value = "id", required = false) Long id) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.fbaReturnInit(id, userId, companyId);
    }


    @UserSessionRequired
    @GetMapping("/printBarCodePdf")
    @ApiOperation(value = "下载产品标", notes = "下载产品标")
    @ApiImplicitParams({@ApiImplicitParam(name = "length", value = "长",required = true),
            @ApiImplicitParam(name = "width", value = "宽", required = true),
            @ApiImplicitParam(name = "id", value = "入库单id", required = true)})
    public void printBarCodePdf(HttpServletRequest request, HttpServletResponse response)  {
        String length = request.getParameter("length");
        String width = request.getParameter("width");
        String id = request.getParameter("id");

        Map<String, String> map = new HashMap<>();

        String commoditySku = request.getParameter("commoditySku");
        String storageSku = request.getParameter("storageSku");
        String fnSku = request.getParameter("fnSku");
        String madeInChina = request.getParameter("madeInChina");
        String printDate = request.getParameter("printDate");
        String productName = request.getParameter("productName");
        String productSpec = request.getParameter("productSpec");

        if (StringUtils.isNotBlank(commoditySku)) {
            map.put("commoditySku", commoditySku);
        }
        if (StringUtils.isNotBlank(storageSku)) {
            map.put("storageSku", storageSku);
        }
        if (StringUtils.isNotBlank(fnSku)) {
            map.put("fnSku", fnSku);
        }
        if (StringUtils.isNotBlank(madeInChina)) {
            map.put("madeInChina", madeInChina);
        }
        if (StringUtils.isNotBlank(printDate)) {
            map.put("printDate", printDate);
        }
        if (StringUtils.isNotBlank(productName)) {
            map.put("productName", productName);
        }
        if (StringUtils.isNotBlank(productSpec)) {
            map.put("productSpec", productSpec);
        }


        service.printBarCodePdf(map, Long.parseLong(id),Integer.parseInt(length), Integer.parseInt(width),response);
    }
}

